package main

import (
	"fmt"
)

func writeData(data chan int)  {
	for i:=2;i<=80000;i++ {
		data <- i
	}
	close(data)
}

func GetPrime(data chan int,result chan int,nums chan int)  {
	
	for {
		num,ok := <-data
		if !ok{
			break
		}
		for i:=2;i<num;i++ {
			if num % i == 0 {
				break
			}
			if i == num-1{
				result <- num
			}
		}		
	}	
	nums <- 0  //这里刚开始放错了位置，导致一直panic
}

func main()  {
	var data chan int
	var result chan int
	var nums chan int

	result = make(chan int,40000)
	nums = make(chan int,4)
	data = make(chan int,1000)

	go writeData(data)

	for i:=0;i<4;i++ {
		go GetPrime(data,result,nums)
	}
	
	go func ()  {
		for i:=0;i<4;i++ {
			<-nums
		}
	
		close(result)
	}()
	
	for {
		num,ok := <-result
		if ok {
			fmt.Printf("素数：%d\n",num)
		}else {
			break
		}
	}
}
